//
//  GLPopCustomAnimation.m
//  ZTRouter
//
//  Created by 黄露 on 2019/6/6.
//  Copyright © 2019 huanglu. All rights reserved.
//

#import "GLPopCustomAnimation.h"

@implementation GLPopCustomAnimation

- (void)setToAnimation:(id<UIViewControllerContextTransitioning>)contextTransition
{
    
    UIView *containerView = contextTransition.containerView;
    UIViewController *fromVC = [contextTransition viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [contextTransition viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *fromView = [contextTransition viewForKey:UITransitionContextFromViewKey] ?: fromVC.view;
    UIView *toView = [contextTransition viewForKey:UITransitionContextToViewKey] ?: toVC.view;
    [containerView addSubview:fromView];
    [containerView addSubview:toView];
    toView.frame = CGRectMake(-CGRectGetWidth(containerView.bounds), 0, CGRectGetWidth(containerView.bounds), CGRectGetHeight(containerView.bounds));
    containerView.backgroundColor = [UIColor clearColor];
    [UIView animateWithDuration:self.duration
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut animations:^{
                            CGRect endFrame = toView.frame;
                            endFrame.origin.x = 0;
                            toView.frame = endFrame;
                        } completion:^(BOOL finished) {
                            [contextTransition completeTransition:!contextTransition.transitionWasCancelled];
                        }];
}


- (void)setBackAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIView *containerView = transitionContext.containerView;
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey] ?: fromVC.view;
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey] ?: toVC.view;
    toView.frame = CGRectMake(0, 0, CGRectGetWidth(containerView.bounds), CGRectGetHeight(containerView.bounds));
    fromView.frame = CGRectMake(0, 0, CGRectGetWidth(containerView.bounds), CGRectGetHeight(containerView.bounds));
    [containerView addSubview:toView];
    [containerView addSubview:fromView];
    [UIView animateWithDuration:self.duration animations:^{
        CGRect fromFrame = fromView.frame;
        fromFrame.origin.x = CGRectGetWidth(containerView.bounds);
        fromView.frame = fromFrame;
    } completion:^(BOOL finished) {
        if ([transitionContext transitionWasCancelled]) {
            [containerView addSubview:fromView];
        }
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
    }];
}


@end
